﻿using System.Collections.Generic;
using Microsoft.Practices.ServiceLocation;
using Sherwood.Web;
using SolrNet;
using SolrNet.Commands.Parameters;
using System.Linq;

namespace Sherwood.Content.UpdateScheduler
{
    public class SolrRecordSource : IExistingRecordsSource
    {
        public SolrRecordSourceProvider Provider { get; set; }
        public string ClientId { get; set; }
        public string PrivateKey { get; set; }

        public SolrRecordSource(SolrRecordSourceProvider solrRecordSourceProvider, string clientId, string privateKey)
        {
            Provider = solrRecordSourceProvider;
            ClientId = clientId;
            PrivateKey = privateKey;
        }

        public virtual IEnumerable<IEnumerable<IRecord>> GetRecordPages()
        {
            lock(Provider.SyncRoot)
            {
                var searchClient = Provider.SearchClient;
                searchClient.ClientId = ClientId;
                searchClient.SetPrivateKey(PrivateKey);
                
                searchClient.ExtraParameters.Clear();
                AddSearchParameters(searchClient.ExtraParameters); 

                var solr = ServiceLocator.Current.GetInstance<ISolrOperations<SolrRecord>>();

                var start = 0;
                while(true)
                {
                    var result = solr.Query(SolrQuery.All, GetQueryOptions(start));

                    if(result.Count == 0)
                        yield break;

                    yield return result;

                    start += Provider.PageSize;
                }
            }
        }

        protected virtual void AddSearchParameters(QueryParameterCollection parameters)
        {
            parameters.Add("profile", Provider.SearchProfileName);
        }

        protected virtual QueryOptions GetQueryOptions(int start)
        {
            return new QueryOptions
                       {
                           Start = start,
                           Rows = Provider.PageSize,
                           Fields = {"id", "reference_id"},
                           FilterQueries = {new SolrQuery("source:\"" + ClientId + "\"")}
                       };
        }
    }
}